package rpcjson

import (
	"context"
	"github.com/pkg/errors"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"gykjgit.dccnet.com.cn/chain/swarm/rpcjson/model"
	"io"
	"io/ioutil"
)

type Image struct{}

func (Image) List(req model.ReqImageList, resp *model.RespImageList) error {
	images, err := client.ObtainClient().ImageList(context.Background(), req.Options)
	if nil != err {
		return err
	}
	resp.Images = images
	return nil
}

func (Image) Pull(req model.ReqImagePull, _ *model.RespImagePull) error {
	r, err := client.ObtainClient().ImagePull(context.Background(), req.RefStr, req.Options)
	if nil != err {
		return errors.Wrap(err, "ImagePull error")
	}
	if _, err = io.Copy(ioutil.Discard, r); nil != err {
		return errors.Wrap(err, "io.Discard error")
	}
	return nil
}

func (Image) Remove(req model.ReqImageRemove, resp *model.RespImageRemove) error {
	items, err := client.ObtainClient().ImageRemove(context.Background(), req.ID, req.Options)
	if nil != err {
		return errors.Wrap(err, "ImageRemove error")
	}
	resp.ImageItems = items
	return nil
}

// Tag Tag
func (Image) Tag(req model.ReqImageTag, _ *model.RespImageTag) error { // "busybox:latest", "busybox:test"
	err := client.ObtainClient().ImageTag(context.Background(), req.Source, req.Target)
	if nil != err {
		return errors.Wrap(err, "ImageTag error")
	}
	return nil
}
